﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using SimpleExpression;

namespace SimpleExpression
{
    public class MySQLServerSelectCommandStrategy : SqlSelectCommandStrategy
    {
      
        public MySQLServerSelectCommandStrategy ()
            : base(new MySQLProvider())
        {
            
        }

        public override void  AddPagingClause(PagingExpression expression)
        {
 	         if(expression.Limit > 0)
             {
                 if(expression.Start > 0)
                     this.pagingClause.AppendFormat("{0}, {1}", expression.Start, expression.Limit);
                 else
                     this.pagingClause.AppendFormat("{0}", expression.Limit);
             }
        }

        protected override string GetCommandText()
        {
            StringBuilder builder = new StringBuilder();
            
            builder.Append("SELECT");
            builder.Append(SPACE);
          
            builder.Append(this.selectClause.ToString());
            builder.Append(Environment.NewLine);
            builder.Append(SPACE);
            builder.Append("FROM");
            builder.Append(SPACE);
            builder.Append(this.fromClause.ToString());

            if (this.whereClause.Length > 0)
            {
                builder.Append(Environment.NewLine);
                builder.Append(SPACE);
                builder.Append("WHERE");
                builder.Append(SPACE);
                builder.Append(this.whereClause.ToString());
            }

            if (this.groupByClause.Length > 0)
            {
                builder.Append(Environment.NewLine);
                builder.Append("GROUP BY");
                builder.Append(SPACE);
                builder.Append(this.groupByClause.ToString());
            }

            if (this.orderByClause.Length > 0)
            {
                builder.Append(Environment.NewLine);
                builder.Append("ORDER BY");
                builder.Append(SPACE);
                builder.Append(this.orderByClause.ToString());
            }

            if (this.pagingClause.Length > 0)
            {
                builder.Append(Environment.NewLine);
                builder.Append("LIMIT");
                builder.Append(SPACE);
                builder.Append(this.pagingClause.ToString());
            }

            return builder.ToString();
        }
    }
}
